import axios from 'axios'
import { getToken } from '@/utils/auth'
import { toast } from '@/utils/message'
import store from '@/store'

const instance = axios.create({
  baseURL: '/api',
  timeout: 5000,
})

instance.interceptors.request.use(
  function (config) {
    const token = getToken()
    if (token) {
      config.headers['token'] = token
    }
    return config
  },
  function (err) {
    return Promise.reject(err)
  }
)

instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (err) {
    const msg = err.response.data.msg || '请求失败'
    // 服务端token失效情况，强制退出
    if (msg === '非法token，请先登录！') {
      store.dispatch('logoutAction').finally(() => {
        location.reload()
      })
    }

    // 错误统一处理
    toast(msg, 'warning')
    return Promise.reject(err)
  }
)

export default instance
